package Service;


import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

/**
 * @Description:实时在线学生名单
 * @Author: 杨淮尊
 * @Date: 2020/4/28
 **/
@ServerEndpoint("/ws/countStu")
public class BitCoinServer {
    //当前连接的SessionID
    private Session sessions;
    //房间内成员容器
    private static Collection<Session> servers = Collections.synchronizedCollection(new ArrayList<Session>());

    /**
     * 建立连接时触发事件
     * @Param: [session]
     * @Return: void
     * @Author: yhz
     * @Date: 2020/4/29 14:12
     */
    @OnOpen
    public void onOpen(Session session) throws IOException {
        this.sessions=session;
        System.out.println("连接建立成功 当前人数:"+servers.size());
        servers.add(session);
        String info1 = "{\n" +
                "\t\"name\": \"yhz\",\n" +
                "\t\"total\": \""+servers.size()+"\"\n" +
                "}";
        sendTextMsg(info1);
    };

    /**
     * 关闭连接触发事件
     * @Return: void
     * @Author: yhz
     * @Date: 2020/4/29 14:13
     */
    @OnClose
    public void onClose() throws IOException {
        System.out.println("连接关闭");
        servers.remove(sessions);
        String info1 = "{\n" +
                "\t\"name\": \"zlc\",\n" +
                "\t\"total\": \""+servers.size()+"\"\n" +
                "}";
        sendTextMsg(info1);
    }

    /**
     * 发生异常触发事件
     * @Param: [error]
     * @Return: void
     * @Author: yhz
     * @Date: 2020/4/29 14:13
     */
    @OnError
    public void onError(Throwable error){
        System.out.println("发生错误");
        error.printStackTrace();
    }

    /**
     * 发送信息
     * @Param: [msg]
     * @Return: void
     * @Author: yhz
     * @Date: 2020/4/29 14:13
     */
    private void sendTextMsg(String msg) {
        for (Session session : servers) {
            session.getAsyncRemote().sendText(msg);
        }
    }

}
